//
//  NetworkTools.m
//  RZIM
//
//  Created by reyzhang on 2021/7/26.
//

#import "NetworkTools.h"
#import <AFNetworking/AFNetworking.h>
#import "RZKitUtility.h"
#import "RZIMConfig.h"

@implementation NetworkTools

+ (void)configManager:(AFHTTPSessionManager *)manager {
    //设置加载时间
    manager.requestSerializer.timeoutInterval = TIMEOUT;
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kAuthTokenKey];
    if (token.length > 0) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    }
}


#pragma mark 请求数据传递方式为form-data格式
+ (void)get:(NSString *)url parameters:(NSDictionary *)parameters succes:(RZSuccessBlock)success failure:(RZFailureBlock)failure {
    [self requestWithMethod:HTTPMethodGET url:url parameters:parameters succes:success failure:failure];
}



+ (void)post:(NSString *)url parameters:(NSDictionary *)parameters succes:(RZSuccessBlock)success failure:(RZFailureBlock)failure {
    [self requestWithMethod:HTTPMethodPOST url:url parameters:parameters succes:success failure:failure];
}


/**
 请求数据为form-data格式
 */
+ (void)requestWithMethod:(NetworkHTTPMethod)method url:(NSString *)url parameters:(NSDictionary *)parameters succes:(RZSuccessBlock)success failure:(RZFailureBlock)failure{
    
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] init];
    [self configManager:manager];
    
    
    //    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置请求返回的数据格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json",@"multipart/form-data",@"application/x-www-form-urlencoded", nil];
    
    
    NSURLSession *managerSession = manager.session;
    if (method == HTTPMethodPOST) {
        
        [manager POST:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            
            //解决AFHttpSessionManager和NSURLSession 之间的循环引用问题 reyzhang
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }else if (method == HTTPMethodGET) {
        [manager GET:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }
    
    
}



#pragma mark 请求数据传递方式为json格式
+ (void)getjson:(NSString *)url parameters:(NSDictionary *)parameters succes:(RZSuccessBlock)success failure:(RZFailureBlock)failure  {
    [self jsonRequestWithMethod:HTTPMethodGET url:url parameters:parameters succes:success failure:failure];
}

//body里面有json串
+ (void)postjson:(NSString *)url parameters:(NSDictionary *)parameters succes:(RZSuccessBlock)success failure:(RZFailureBlock)failure {
    [self jsonRequestWithMethod:HTTPMethodPOST url:url parameters:parameters succes:success failure:failure];
}

/**
 请求数据为json格式
 */
+ (void)jsonRequestWithMethod:(NetworkHTTPMethod)method url:(NSString *)url parameters:(NSDictionary *)parameters succes:(RZSuccessBlock)success failure:(RZFailureBlock)failure {
    
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] init];
    
    //body里面含有json串填写这个
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self configManager:manager];
    
    NSString *methodStr = method == HTTPMethodPOST ? @"POST" : @"GET";
    [manager.requestSerializer requestWithMethod:methodStr URLString:url parameters:parameters error:nil];
    
    //设置请求返回的数据格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/html", @"text/javascript", nil];
    
    NSURLSession *managerSession = manager.session;
    if (method == HTTPMethodPOST) {
        [manager POST:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }else {
        [manager GET:url parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if (success) {
                success(responseObject);
            }
            [managerSession finishTasksAndInvalidate];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [managerSession finishTasksAndInvalidate];
        }];
    }
    
}


//这是个字典转json数据的方法
+(NSString *)convertToJsonData:(NSDictionary *)dict{
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    return mutStr;
    
}


/**
 下载文件
 */
+ (void)downloadFileWithUrl:(NSURL *)remoteUrl
            completeHandler:(void(^)(NSURL *localUrl))block {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSString *urlStr = remoteUrl.absoluteString;
    NSString *fileName = [urlStr lastPathComponent]; //获取文件名称
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //判断是否存在
    if([self isFileExist:fileName]) {
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
        !block ?: block(url);
    }else {
        
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
            
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            !block ?: block(filePath);
        }];
        [downloadTask resume];
    }
}



//判断文件是否已经在沙盒中存在
+ (BOOL)isFileExist:(NSString *)fileName
{
    return [self isFileExist:fileName needDel:NO];
}


//判断文件是否已经在沙盒中存在
+ (BOOL)isFileExist:(NSString *)fileName needDel:(BOOL)needDel
{
    //document 沙盒
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    
    //如果找到，并且允许删除
    if (result && needDel) {
        [fileManager removeItemAtPath:filePath error:nil];
    }
    return result;
}

/**
 上传
 */
+ (void)uploadWithURL:(NSString *)URL
                files:(NSArray *)fileArray
             progress:(RZProgressBlock)progress
              success:(RZSuccessBlock)success
              failure:(RZFailureBlock)failure {
    
    
    //显示状态栏的网络指示器
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] init];
    //设置加载时间
    manager.requestSerializer.timeoutInterval = TIMEOUT;
    
    //设置请求返回的数据格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSURLSession *managerSession = manager.session;
    [manager POST:URL parameters:@{} headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        
        for (int i = 0; i<fileArray.count; i++) {
            
//            NSString *formKey = [NSString stringWithFormat:@"files",(long)i];
            id file = fileArray[i];
            if ([file isKindOfClass:[UIImage class]]) {
                NSString *name = [NSString stringWithFormat:@"%@.png",[RZKitUtility get13TimeStemp]];
                NSData *data = UIImageJPEGRepresentation(file, RZIMConfigCenter.ui.imageMessageCompressRatio);
                NSString *type = @"image/png";
                [formData appendPartWithFileData:data name:@"files" fileName:name mimeType:type];
            }else if ([file isKindOfClass:[NSString class]]) {
                NSURL *url = [NSURL fileURLWithPath:file];
                NSString *type = @"";
                NSString *name = @"";
                if (url && [url.pathExtension isEqualToString:@"mp3"]) { //mp3音频格式
                    type = @"audio/mpeg";
                    name = [NSString stringWithFormat:@"%@.mp3",[RZKitUtility get13TimeStemp]];
                }else if ( url && [url.pathExtension isEqualToString:@"mp4"]) { //mp4视频格式
                    type = @"video/mp4";
                    name = [NSString stringWithFormat:@"%@.mp4",[RZKitUtility get13TimeStemp]];
                }else if (url && [url.pathExtension isEqualToString:@"wav"]) { //wav 无损压缩 音频格式
                    type = @"audio/x-wav";
                    name = [NSString stringWithFormat:@"%@.wav",[RZKitUtility get13TimeStemp]];
                }else if (url && [url.pathExtension isEqualToString:@"amr"]) { //amr 有损压缩 音频格式
                    type = @"audio/amr";
                    name = [NSString stringWithFormat:@"%@.amr",[RZKitUtility get13TimeStemp]];
                }
                NSData *data = [NSData dataWithContentsOfFile:file];
                [formData appendPartWithFileData:data name:@"files" fileName:name mimeType:type];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"---上传进度--- %@",uploadProgress);
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress) : nil;
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"```上传成功``` %@",responseObject);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:nil];
        success ? success(json) : nil;
        [managerSession finishTasksAndInvalidate];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"xxx上传失败xxx %@", error);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        failure ? failure(error) : nil;
        [managerSession finishTasksAndInvalidate];
    }];
}

@end
